package com.ww.httpclient;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class HttpClientUploadAndDownloadDemo {

    public static void main(String[] args) throws IOException {
        // ========================================上传========================================
        /**
         * 在HttpClient中实现上传功能非常方便，通过MultipartEntityBuilder直接构建HttpEntity即可
         */

        // 上传文件
        File file = new File("");
        // 创建对象
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        // 添加二进制消息
        multipartEntityBuilder.addBinaryBody("file", file);

        // 也可以添加文本消息
        ContentType contentType = ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8);
        multipartEntityBuilder.addTextBody("name", "张三", contentType);

        // 通过MultipartEntityBuilder构建消息体
        HttpEntity httpEntity = multipartEntityBuilder.build();
        HttpPost httpPost = new HttpPost("http://localhost:8080/...");
        httpPost.setEntity(httpEntity);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);

        int code = response.getCode();
        if (code == HttpStatus.SC_OK) {
            System.out.println("请求响应成功");
        }

        // ========================================下载========================================
        HttpGet httpGet = new HttpGet("http://localhost:8080/...");
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getCode() == HttpStatus.SC_OK) {
            System.out.println("下载成功");

            // 获取下载文件的文件名，此处的File-Name头信息，需要在服务端进行自定义
            Header header = httpResponse.getFirstHeader("File-Name");
            String value = header.getValue();

            // 读取数据
            byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity());
            try (OutputStream outputStream = new FileOutputStream("...")) {
                outputStream.write(bytes);
                outputStream.flush();
            }
        }
    }
}
